<?php

namespace api\modules\v1\models;

use api\func\func;
use Yii;
use api\common\models\Common;
use yii\web\NotFoundHttpException;
use \yii\caching\FileDependency;

class Category extends Common
{

    public function fields()
    {
        return [
            'catid', //分类id
            'catname', //分类名称
            'modelid', //模块类型 1 文章模型  14 视频模型
            //'ismenu', //是否是菜单
            'parentid',
        ];
    }

    public static function tableName()
    {
        return '{{%category}}';
    }


    /*
     * 根据id 返回数组信息
     * @param $ids
     */
    public function getId2Info($ids){
        if($ids == '') return [];
        $data = self::find()->select('catid,catname')->where('catid in ('.$ids.')')->asArray()->all();
        return $data;
    }

    public static function getTree($data, $pId)
    {
        $tree = '';
        foreach($data as $k => $v)
        {
            if($v['parentid'] == $pId)
            {         //父亲找到儿子
                $v['_child'] = self::getTree($data, $v['catid']);
                $tree[] = $v;
                //unset($data[$k]);
            }
        }
        return $tree;
    }


    /*
     * 获取收藏栏目
     * @return array|\yii\db\ActiveRecord[]
     * @throws \yii\web\NotFoundHttpException
     */
    public function getFormatCategory_v2(){
        $field = 'catid,isdefault,catname,modelid,parentid';
        $category = self::find()->where(['type'=>0,'isarea'=>0,'ismenu'=>1])->select($field)->orderBy('listorder asc')->asArray()->all();
        $areaList = $this->_getAreaList(); //获取所有的地区栏目
        $data = [];
        $collect = [];//收藏的普通栏目
        $collect_area = [];//收藏的地区栏目
        $data_default_area = []; //默认的地区栏目

        $user = $this->getTokenUserId();
        if($user !='' && is_array($user) && $user['collect_category'] != '') { //处于登录状态且收藏列表不为空  取出 收藏的栏目
            $collect_category = explode('|',$user['collect_category']);

/*            foreach($category as $key=>$value){
                if(in_array($value['catid'],$collect_category)){ //普通栏目
                    $collect[$value['catid']] = $value;
                    unset($category[$key]);
                }
            }*/

            //整合排序
            $_category = [];
            foreach($category as $key=>$value){
                $_category[$value['catid']] = $value;
            }
            foreach($collect_category as $value){
                if(isset($_category[$value])){
                    $collect[] = $_category[$value];
                    unset($_category[$value]);
                }
            }
            $category = $_category;
            //整合排序

/*            foreach($areaList as $key=>$value){ //地区栏目
                if(in_array($value['catid'],$collect_category)){
                    $collect_area[] = $value;
                    //unset($areaList[$key]);
                }
            }*/

            //整合排序
            $_areaList = [];
            foreach($areaList as $key=>$value){
                $value = str_replace(',','_',$value);
                $_areaList[$value['catid']] = $value;
            }

            foreach($collect_category as $value){
                $value = str_replace(',','_',$value);
                if(isset($_areaList[$value])){
                    $_areaList[$value]['catid'] = str_replace('_',',',$_areaList[$value]['catid']);
                    $collect_area[] = $_areaList[$value];
                }
            }
            //整合排序

        }else{ //处于未登录状态 取出默认栏目
            foreach($category as $key=>$value){
                if($value['isdefault'] == 1){
                    $collect[] = $value;
                    unset($category[$key]);
                }
            }
        }
        $category = array_values($category);


        //针对收藏栏目 必须显示在第一个
/*        foreach($collect as $key=>$value){
            if($value['catid'] == 555){
                $recommend_cate = $value;
                unset($collect[$key]);
            }
        }
        array_unshift($collect,$recommend_cate);*/

        //生成拼音地区栏目分组
        $data_py = [];
        for($i=65;$i<=90;$i++){
            $chr = chr($i);
            $data_py[$chr] = ['name'=>$chr,'data'=>[]];
        }

        //整合分组
        foreach($areaList as $key=>$value){
            $first = func::getfirstchar($value['catname']);
            $data_py[$first]['data'][] = $value;
            if($value['isdefault'] == 1){
                $data_default_area[] = $areaList[$key];
            }
        }
        $data_py = array_values($data_py);

        $data_area = [
            'py' =>$data_py,
            'isdefault'=>$data_default_area
        ];


        $data['collect']['default'] = $collect;
        $data['collect']['area'] = $collect_area;
        $data['default'] = $category;
        $data['area'] = $data_area;
        return $data;
    }


    /*
     * 获取收藏栏目
     * @return array|\yii\db\ActiveRecord[]
     * @throws \yii\web\NotFoundHttpException
     */
    public function getFormatCategory(){
        $field = 'catid,isdefault,catname,modelid,parentid';
        $category = self::find()->where(['type'=>0,'isarea'=>0,'ismenu'=>1])->select($field)->orderBy('listorder asc')->asArray()->all();
        $data = [];
        $collect = [];//收藏的栏目
        $user = $this->getTokenUserId();
        if($user !='' && is_array($user) && $user['collect_category'] != '') { //处于登录状态且收藏列表不为空  取出 收藏的栏目
            $collect_category = explode(',',$user['collect_category']);
            foreach($category as $key=>$value){
                if(in_array($value['catid'],$collect_category)){
                    $collect[] = $value;
                    unset($category[$key]);
                }
            }
        }else{ //处于未登录状态 取出默认栏目
            foreach($category as $key=>$value){
                if($value['isdefault'] == 1){
                    $collect[] = $value;
                    unset($category[$key]);
                }
            }
        }
        $category = array_values($category);
        $data['collect'] = $collect;
        $data['default'] = $category;
        return $data;
    }


    /*
     * 获取地区id
     * @return array|null|\yii\db\ActiveRecord
     * @throws NotFoundHttpException
     */
    public function getArea(){
        $area = Yii::$app->request->get('area');
        if($area_id = self::find()->select('catid')->where(['catname'=>$area,'isarea'=>1])->asArray()->one()){
            $area_data = self::find()->where(['parentid'=>$area_id['catid'],'isarea'=>1])->select('catid,isdefault,catname,modelid,parentid')->asArray()->all();
            $area_catid = '';
            foreach($area_data as $value){
                $area_catid .= $value['catid'].',';
            }
            $area_catid = substr($area_catid,0,-1);
            $tmp_data['catid'] = $area_catid;
            $tmp_data['catname'] = $area.'云';
            $tmp_data['modelid'] = '';
            $tmp_data['parentid'] = $area_data[0]['parentid'];
            $tmp_data['_child'] = '';
            return $tmp_data;
        }else{
            throw new NotFoundHttpException('未找到地区记录.');
        }
    }

    public function _getAreaList(){
        $field = 'catid,isdefault,catname,modelid,parentid';
        $category = self::find()->where(['type'=>0,'isarea'=>1])->select($field)->orderBy('listorder asc')->asArray()->all();
        if(count($category) == 0){
            return [];
        }
        $category = array_values($category);
        $category = self::getTree($category,0);
        $tmp_data = $category[0]['_child'];
        $data = [];
        foreach($tmp_data as $key=>$value){
            if($value['_child'] != ''){
                $area_catid = '';
                foreach($value['_child'] as $v){
                    $area_catid .= $v['catid'].',';
                }
                $area_catid = substr($area_catid,0,-1);
                $data[$key]['catid'] = $area_catid;
                $data[$key]['catname'] = $value['catname'].'云';
                $data[$key]['modelid'] = '';
                $data[$key]['parentid'] = $value['parentid'];
                $data[$key]['isdefault'] = $value['isdefault'];
                $data[$key]['_child'] = '';
            }else{
                unset($data[$key]);
            }
        }
        return $data;
    }


    public function getAreaList(){
        $cahce = Yii::$app->cache;
        $cacheKey = md5('areaList');
        $_data = $cahce->get($cacheKey);
        if ($_data === false) {
            $field = 'catid,isdefault,catname,modelid,parentid';
            $category = self::find()->where(['type'=>0,'isarea'=>1])->select($field)->orderBy('listorder asc')->asArray()->all();
            $category = array_values($category);
            $category = self::getTree($category,0);
            $data = [];
            $data_py = [];
            $data_default = [];

            for($i=65;$i<=90;$i++){
                $chr = chr($i);
                $data_py[$chr] = ['name'=>$chr,'data'=>[]];
            }

            $tmp_data = $category[0]['_child'];
            foreach($tmp_data as $key=>$value){
                if($value['_child'] != ''){
                    $area_catid = '';
                    foreach($value['_child'] as $v){
                        $area_catid .= $v['catid'].',';
                    }
                    $area_catid = substr($area_catid,0,-1);
                    $data[$key]['catid'] = $area_catid;
                    $data[$key]['catname'] = $value['catname'].'云';
                    $data[$key]['modelid'] = '';
                    $data[$key]['parentid'] = $value['parentid'];
                    $data[$key]['isdefault'] = $value['isdefault'];
                    $data[$key]['_child'] = '';

                    if($value['isdefault'] == 1){
                        $data_default[] = $data[$key];
                    }

                }else{
                    unset($data[$key]);
                }
            }

            //整个分组
            foreach($data as $value){
                $first = func::getfirstchar($value['catname']);
                $data_py[$first]['data'][] = $value;
            }
            $data_py = array_values($data_py);

            $_data = [
                'py' =>$data_py,
                'isdefault'=>$data_default
            ];

            $cahce->set($cacheKey, $_data, Yii::$app->params['cache_area_list'], new FileDependency(['fileName' => 'cache.txt']));
        }
        return $_data;
    }

}
